
import { useState } from "react";
import { useRef } from "react";
import classnames from "classnames";
import './home.css';
const list = [
  { id: 1, name: "标题1", comment: 102, time: "1"},
  { id: 2, name: "标题2", comment: 120, time: "5"},
  { id: 3, name: "标题3", comment: 100, time: "3"},
  { id: 4, name: "标题4", comment: 103, time: "6"},
  { id: 5, name: "标题5", comment: 10, time: "2"}
];

const tabs = [
    { type: '1', name: "最新" },
    { type: '2', name: "最热" }
  ];
  
function App () {
  // 评论内容 
  const [commonList, setCommonList] = useState(list);
  const delCom = (id) => {
    const newList = commonList.filter(item => item.id!== id);
    setCommonList(newList);
  }

  //  tab切换
  //   1.className={type === item.type ? "active" : ""}
  //   2.classnames库 classnames= {className('nav-item', {active: type === item.type })}
  const [type, setTabs] = useState('1');
  const changeTabs = (type) => {
    console.log(type);
    setTabs(type);
    // 排序列表
    if(type === '1') {
      const newList = commonList.sort((a,b)=> b.time - a.time);
      setCommonList(newList);
    } else {
      const newList = commonList.sort((a,b)=> b.comment - a.comment);
      setCommonList(newList);
    }
  }

  // 发表评论
  const [content, setContent] = useState('');
  const inputRf = useRef();
  const handlePush = () => {
    const newList = [...commonList, {id: commonList.length + 1, name: "张三", comment: content, time: "1"}];
    setCommonList(newList);
    // 清空评论内容
    setContent('');
    // 重新聚焦
    inputRf.current.focus();
  }

  return(
    <div>
     <div>
        <textarea
         ref={inputRf}
         cols="30"
         rows="10"
         placeholder="请输入评论内容"
         value={content}
         onChange={(e)=> setContent(e.target.value)}
         ></textarea>
         <button onClick={handlePush}>发布</button>
     </div>
     <div>
        { tabs.map(item =>
            <span
            key={item.type}
            className= {classnames('nav-item', {active: type === item.type })}
            onClick={()=> changeTabs(item.type)}
            >{item.name} | 
            </span>
        )}
     </div>
     <div>
        { commonList.map(item => 
          <div key={item.id} style={{margin: "10px 0"}}>
            <span>评论人: {item.name}</span>
            <span>评论: {item.comment}</span>
            <button onClick={()=> delCom(item.id)}>删除</button>
          </div>
        )}
      </div>
    </div>
  )
}
export default App;
